package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SContentCount;
import com.py.credit.entity.SContentInfo;
import com.py.credit.entity.SContentLogCount;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.TreeObj;
import com.py.credit.service.*;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping(value = "/category")
public class CategoryController {

    private static final int ZERO = 0;

    private static final String ZERO_STR = "0";

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ScontentService sContentService;

    @Autowired
    private SContentLogService sContentLogService;

    @Autowired
    private RemoteBaseService remoteBaseService;

    @Autowired
    private ShareLogService shareLogService;

    /**
     * @api {get} /category/getScontentList.json 获取共享目录列表
     * @apiName getScontentList
     * @apiVersion 0.0.1
     * @apiGroup 共享目录
     * @apiParam {String} name 视图id(可选)
     * @apiParam {int} limit 每页展示条数 (必需)
     * @apiParam {int} page 当前页数 (必需)
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {Object[]} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":2,"data":[{"id":1,"status":null,"maintainer":"superadmin","updateTime":1524017339000,"name":"一站式查询","description":"一站式查询"},{"id":2,"status":null,"maintainer":"superadmin","updateTime":1523270988000,"name":"授权查询","description":"授权查询"}]}
     */
    @RequestMapping(value = "/getScontentList.json")
    public RestServiceResult<List<SContentInfo>> getTableList(
            @RequestParam(value = "name", defaultValue = "", required = true) String name, Page page) {

        List<SContentInfo> tableList = sContentService.getListForPage(name, page);

        return new RestServiceResult<List<SContentInfo>>(page.getTotalCount(), tableList);

    }

    /**
     * @api {get} /category/getScontentName.json 获取共享目录名称
     * @apiName getScontentName
     * @apiVersion 0.0.1
     * @apiGroup 共享目录
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String[]} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"data":["一站式查询","授权查询"]}
     */

    @RequestMapping(value = "/getScontentName.json")
    public RestServiceResult<List<String>> getScontentName() {

        return new RestServiceResult<List<String>>(sContentService.getScontentName());

    }

    /**
     * @api {get} /category/editDetail.json 获取共享目录编辑详情数据
     * @apiName editDeatil
     * @apiVersion 0.0.1
     * @apiGroup 共享目录
     * @apiParam {int} infoId 共享目录id(必需)
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {Object[]} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"data":[{"id":"100000","rootId":null,"name":"法人库","url":null,"type":"K","pId":"0","sort":null,"children":null,"extend":null,"icon":null,"checked":"false","nocheck":null,"open":false,"isParent":null},{"id":"100001","rootId":null,"name":"自然人库","url":null,"type":"K","pId":"0","sort":null,"children":null,"extend":null,"icon":null,"checked":"false","nocheck":null,"open":false,"isParent":null},{"id":"R4M1523501430161","rootId":null,"name":"asdf","url":null,"type":"L","pId":"100001","sort":null,"children":null,"extend":null,"icon":null,"checked":"false","nocheck":null,"open":false,"isParent":null},{"id":"R4M1523501430162","rootId":null,"name":"444","url":null,"type":"L","pId":"R4M1523501430161","sort":null,"children":null,"extend":null,"icon":null,"checked":"false","nocheck":null,"open":false,"isParent":null}]}
     */
    @RequestMapping(value = "/editDeatil.json")
    public RestServiceResult<List<TreeObj>> getEditDeatil(
            @RequestParam(value = "infoId", defaultValue = "", required = true) int infoId) {

        List<TreeObj> detail = sContentService.getEditDeatil(infoId);

        return new RestServiceResult<List<TreeObj>>(detail);

    }

    /**
     * @api {get} /category/getInfoDetail.json 获取共享目录单条信息
     * @apiName getInfoDeatil
     * @apiVersion 0.0.1
     * @apiGroup 共享目录
     * @apiParam {int} infoId 共享目录id(必需)
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"data":{"id":29,"useImmediately":null,"tableNum":0,"colNum":0,"pVersion":null,"type":null,"status":"Y","maintainer":"superadmin","updateTime":1524216303000,"name":"一站式查询","description":"一站式查询"}}
     */
    @RequestMapping(value = "/getInfoDeatil.json")
    public RestServiceResult<SContentInfo> getInfoDeatil(
            @RequestParam(value = "infoId", defaultValue = "", required = true) int infoId) {

        SContentInfo sContentInfo = sContentService.getInfoDeatil(infoId);

        return new RestServiceResult<SContentInfo>(sContentInfo);

    }

    /**
     * @api {get} /category/getSharingContentTreeMenu.json 获取共享目录树状图数据
     * @apiName getSharingContentTreeMenu
     * @apiVersion 0.0.1
     * @apiGroup 共享目录
     * @apiParam {String} infoId 共享目录id(必需)
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {Object[]} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"data":[{"id":"100000","rootId":null,"name":"法人库","url":null,"type":"K","pId":"0","sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":"100001","rootId":null,"name":"自然人库","url":null,"type":"K","pId":"0","sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":"100002","rootId":null,"name":"非企业法人库","url":null,"type":"K","pId":"0","sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":"R4M1523501430161","rootId":null,"name":"asdf","url":null,"type":"L","pId":"100001","sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":"R4M1523501430162","rootId":null,"name":"444","url":null,"type":"L","pId":"R4M1523501430161","sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null}]}
     */

    @RequestMapping(value = "/getSharingContentTreeMenu.json")
    public RestServiceResult<List<TreeObj>> getSharingContentTreeMenu(
            @RequestParam(value = "infoId", defaultValue = "", required = true) String infoId) {

        return new RestServiceResult<List<TreeObj>>(sContentService.getSharingContentTree(infoId));

    }

    /**
     * @api {get} /category/getColumnNodes.json 获取表的列信息
     * @apiName getColumnNodes
     * @apiVersion 0.0.1
     * @apiGroup 共享目录
     * @apiParam {String} tableId 表id(必需)
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {Object[]} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * <p>
     * {"code":0,"msg":null,"data":[{"id":"1323","rootId":null,"name":"企业名称","url":null,"type":"M","pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":"true","nocheck":null,"open":false,"isParent":null},{"id":"1324","rootId":null,"name":"统一社会信用代码","url":null,"type":"M","pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":"true","nocheck":null,"open":false,"isParent":null},{"id":"1325","rootId":null,"name":"工商登记码","url":null,"type":"M","pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":"true","nocheck":null,"open":false,"isParent":null},{"id":"1326","rootId":null,"name":"组织机构代码","url":null,"type":"M","pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":"true","nocheck":null,"open":false,"isParent":null},{"id":"1327","rootId":null,"name":"税务登记号","url":null,"type":"M","pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":"true","nocheck":null,"open":false,"isParent":null}]}
     */
    @RequestMapping(value = "/getColumnNodes.json")
    public RestServiceResult<List<TreeObj>> getColumnNodes(
            @RequestParam(value = "tableId", defaultValue = "", required = true) String tableId) {

        return new RestServiceResult<List<TreeObj>>(categoryService.getColumnNodes(tableId));

    }

    /**
     * 添加共享目录
     *
     * @param tableId
     * @return
     */

    /**
     * @api {get} /category/addSharingContent.json 添加共享目录
     * @apiName addSharingContent
     * @apiVersion 0.0.1
     * @apiGroup 共享目录
     * @apiParam {String}description 共享目录描述 (必需)
     * @apiParam {String}nodes 共享目录节点 (必需)
     * @apiParam {String}name 共享目录名称 (必需)
     * @apiParam {String}type 共享目录类型 (必需)
     * @apiParamExample {json} 请求参数示例
     * {"name":"一站式查询","description":"一站式查询共享目录","type":"YZS","nodes":[{"id":"100000","name":"法人库","type":"K","pId":"0"},{"id":"1","name":"企业基础信息","type":"L","code":"qyjcxx","pId":"100000"},{"id":"2","name":"变更信息","type":"L","code":"bgxx","pId":"1"},{"id":"12","name":"企业基础信息","type":"T","code":"JBXX","pId":"2"}]}
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */

    @RequestMapping(value = "/addSharingContent.json")
    public RestServiceResult<String> addSharingContent(SContentInfo sContentInfo,
                                                       @RequestParam(value = "nodes", defaultValue = "", required = true) String nodes,
                                                       HttpServletRequest request) {

        String userName = null;

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo) {

                userName = userInfo.getUsername();
            } else {

                ExceptionLogger.error("CategoryController#addSharingContent", "未获取到当前用户信息！");

            }

        } else {

            ExceptionLogger.error("CategoryController#addSharingContent", "未获取到当前用户信息！");
        }

        sContentInfo.setMaintainer(userName == null ? "" : userName);

        if (StringUtils.isBlank(sContentInfo.getName())) {

            throw new ServiceException("共享目录名称不能为空");

        }
        if (StringUtils.isBlank(sContentInfo.getDescription())) {
            throw new ServiceException("共享目录名称不能为空");
        }

        List<TreeObj> nodeList = JSONArray.parseArray(nodes, TreeObj.class);

        if (CollectionUtils.isEmpty(nodeList)) {
            throw new ServiceException("目录不能为空");
        }

        if (sContentService.typeExist(sContentInfo.getType())) {
            throw new ServiceException("目录类型已存在");
        }

        sContentService.add(sContentInfo, nodeList);

        return new RestServiceResult<String>();

    }

    /**
     * @api {get} /category/updateSharingContent.json 更新共享目录
     * @apiName updateSharingContent
     * @apiVersion 0.0.1
     * @apiGroup 共享目录
     * @apiParam {String}description 共享目录描述 (必需)
     * @apiParam {String}nodes 共享目录节点 (必需)
     * @apiParam {String}name 共享目录名称 (必需)
     * @apiParam {int}id 共享目录id (必需)
     * @apiParam {String}type 共享目录类型 (必需)
     * @apiParamExample {json} 请求参数示例
     * {"id":"1","name":"一站式查询","description":"一站式查询共享目录","type":"YZS","nodes":[{"id":"100000","name":"法人库","type":"K","pId":"0"},{"id":"1","name":"企业基础信息","type":"L","code":"qyjcxx","pId":"100000"},{"id":"2","name":"变更信息","type":"L","code":"bgxx","pId":"1"},{"id":"12","name":"企业基础信息","type":"T","code":"JBXX","pId":"2"}]}
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */

    @RequestMapping(value = "/updateSharingContent.json")
    public RestServiceResult<String> updateSharingContent(
            @RequestParam(value = "nodes", defaultValue = "", required = true) String nodes, SContentInfo sContentInfo,
            @RequestParam(value = "id", defaultValue = "", required = true) int id, HttpServletRequest request) {
        RestServiceResult<String> result = new RestServiceResult<String>();
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        String userName = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {

                userName = userInfo.getUsername();
            }

        } else {

            ExceptionLogger.error("CategoryController#updateSharingContent", "未获取到当前用户信息！");

        }

        sContentInfo.setMaintainer(userName == null ? "" : userName);

        if (StringUtils.isBlank(sContentInfo.getName())) {

            throw new ServiceException("共享目录名称不能为空");

        }
        if (StringUtils.isBlank(sContentInfo.getDescription())) {
            throw new ServiceException("共享目录名称不能为空");
        }

        if (StringUtils.isBlank(nodes)) {
            throw new ServiceException("目录不能为空");
        }

        List<TreeObj> nodeList = JSONArray.parseArray(nodes, TreeObj.class);

        sContentService.updateScontent(sContentInfo, nodeList);

        return result;

    }

    /**
     * @api {get} /category/delSharingContent.json 删除共享目录
     * @apiName delSharingContent
     * @apiVersion 0.0.1
     * @apiGroup 共享目录
     * @apiParam {int}infoId 共享目录id(必需)
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */

    @RequestMapping(value = "/delSharingContent.json")
    public RestServiceResult<String> delSharingContent(
            @RequestParam(value = "infoId", defaultValue = "", required = true) int infoId) {
        sContentService.deleteScontent(infoId);
        return new RestServiceResult<String>();
    }

    /**
     * @api {get} /category/getCountShareContentInfo.json 查询数据共享子系统看板数据
     * @apiName getCountShareContentInfo
     * @apiVersion 0.0.1
     * @apiGroup 共享目录
     * @apiParam {String} type 类型(必填) YZS:一站式,XYHC:信用核查,JKSQ:接口授权
     * @apiParamExample {json} 请求参数示例 {"type":"YZS"}
     * @apiSuccess {int} categoryNum 分类数量
     * @apiSuccess {int} tableNum 资源数量
     * @apiSuccess {int} colNum 数据项数量
     * @apiSuccess {String} type 查询目录 YZS:一站式,XYHC:信用核查,JKSQ:接口授权
     * @apiSuccess {JSONObject} queryCount 查询统计结果集
     * @apiSuccess {String} dates 日期数组
     * @apiSuccess {String} counts 统计结果数组
     * @apiSuccessExample {json} 成功返回结果
     * {"categoryNum":1,"tableNum":2,"colNum":30,"sQueryNum":0,"authIntfNum":0,"authQueryNum":0,"intfQueryNum":0,"queryCount":[{"counts":["1","1","0","0","0","0","0","0","0","0","0","0"],"dates":["2018-05","2018-04","2018-03","2018-02","2018-01","2017-12","2017-11","2017-10","2017-09","2017-08","2017-07","2017-06"],"type":"XYHC"},{"counts":["1","1","0","0","0","0","0","0","0","0","0","0"],"dates":["2018-05","2018-04","2018-03","2018-02","2018-01","2017-12","2017-11","2017-10","2017-09","2017-08","2017-07","2017-06"],"type":"YZS"}]}
     */
    @RequestMapping(value = "/getCountShareContentInfo.json")
    @ResponseBody
    public RestServiceResult<SContentCount> getCountShareContentInfo(
            @RequestParam(value = "type", defaultValue = "YZS", required = true) String type) {
        SContentCount sContentCount = new SContentCount();
        // 查询数据共享子系统看板共享目录数据
        SContentInfo sContentInfo = sContentService.getCountShareContentInfo(type);
        if (null != sContentInfo) {
            sContentCount.setCategoryNum(sContentInfo.getCategoryNum());
            sContentCount.setTableNum(sContentInfo.getTableNum());
            sContentCount.setColNum(sContentInfo.getColNum());
        } else {
            // 未查询到共享数据 设置为0
            sContentCount.setCategoryNum(ZERO);
            sContentCount.setTableNum(ZERO);
            sContentCount.setColNum(ZERO);
        }
        // 暂无查询数据 设置为0
        // 1、一站式 2、信用核查 3、外部接口

        sContentCount.setsQueryNum(shareLogService.getQueryCountByType(1));
        sContentCount.setAuthIntfNum(shareLogService.getQueryCountByType(2));
        sContentCount.setAuthQueryNum(shareLogService.getQueryCountByType(3));
        sContentCount.setIntfQueryNum(ZERO);
        // 获取查询统计数据集合
        List<SContentLogCount> counts = sContentLogService.queryCount();
        // 获取最近的12个月
        String[] mouths = getMouths();
        List<JSONObject> queryCount = new ArrayList<JSONObject>();
        for (SContentLogCount count : counts) {
            String[] queryNum = new String[12];
            JSONObject jb = new JSONObject();
            Map<String, String> map = new HashMap<String, String>();
            if (null != count && StringUtils.isNoneEmpty(count.getDates())
                    && StringUtils.isNoneEmpty(count.getCounts())) {
                String[] dates = count.getDates().split(",");
                String[] qCounts = count.getCounts().split(",");
                for (int i = 0; i < dates.length; i++) {

                    int num = map.get(dates[i]) == null ? 0 : Integer.valueOf(map.get(dates[i]));

                    map.put(dates[i], String.valueOf(num + Integer.valueOf(qCounts[i])));
                }
            }
            // 填充统计数据，默认为0
            for (int i = 0; i < 12; i++) {
                if (map.containsKey(mouths[i])) {
                    queryNum[i] = map.get(mouths[i]);
                } else {
                    queryNum[i] = ZERO_STR;
                }
            }
            jb.put("type", count.getType());
            jb.put("dates", mouths);
            jb.put("counts", queryNum);
            queryCount.add(jb);
        }
        sContentCount.setQueryCount(queryCount);
        return new RestServiceResult<SContentCount>(sContentCount);
    }

    /**
     * @return
     * @Function 获取最近的12个月，包含本月
     * @FileName CategoryController.java
     * @MethodName getMouths
     * @Date 2018年5月2日 下午4:29:33
     * @Author Min DongXv
     */
    private String[] getMouths() {
        String[] mouths = new String[12];
        Calendar cal = Calendar.getInstance();
        // 要先+1,才能把本月的算进去
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);
        for (int i = 0; i < 12; i++) {
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); // 逐次往前推1个月
            mouths[11 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) >= 9 ? cal.get(Calendar.MONTH) + 1
                    : "0" + (cal.get(Calendar.MONTH) + 1));
        }
        return mouths;
    }
}
